#include "drv_usart.h"
#include "nst_define.h"
#include "nst_log.h"
#include "stdio.h"
#include "stdint.h"
#include "stdarg.h"
#include "string.h"

#define LOG_UART USART1_PORT

#define MAX_LOG_BUFFER_SIZE 256

static char log_buffer[MAX_LOG_BUFFER_SIZE];

#include "sys_manager.h"
// 日志发送函数
static void port_drv_uart_tx(const char *message)
{
    if(!system_status.uart.uart1_dma_tx_busy)
    {
        drv_usart_send_data(LOG_UART, (uint8_t *)message, strlen(message));        
    }
}

// 生成日志消息
void generate_log_message(const char *format, va_list args)
{
    // 使用 vsnprintf 格式化日志消息
    int log_length = vsnprintf(log_buffer, MAX_LOG_BUFFER_SIZE, format, args);

    // 处理日志消息截断
    if (log_length >= MAX_LOG_BUFFER_SIZE - 2)
    {
        const char *truncate_msg = " [TRUNCATED]";
        size_t truncate_msg_len = strlen(truncate_msg);

        if (truncate_msg_len < MAX_LOG_BUFFER_SIZE - 2)
        {
            strncpy(log_buffer + MAX_LOG_BUFFER_SIZE - truncate_msg_len - 3, truncate_msg, truncate_msg_len);
            log_buffer[MAX_LOG_BUFFER_SIZE - 3] = '\r';
            log_buffer[MAX_LOG_BUFFER_SIZE - 2] = '\n';
            log_buffer[MAX_LOG_BUFFER_SIZE - 1] = '\0';
        }
    }
    else
    {
        // 正确追加 \r\n 到字符串末尾
        if (log_length + 2 < MAX_LOG_BUFFER_SIZE)
        {
            log_buffer[log_length] = '\r';
            log_buffer[log_length + 1] = '\n';
            log_buffer[log_length + 2] = '\0';
        }
    }
}

// 日志函数
void nst_log(const char *format, ...)
{
    va_list args;
    va_start(args, format);
    generate_log_message(format, args);
    va_end(args);

    // 通过串口发送日志消息
    port_drv_uart_tx(log_buffer);
}
